import {
  formatSeconds
} from '../../utils/util.js'

let app = getApp()
Page({
  data: {
    spinShow: false,
    score: 0,
    paperId: null,
    examPaperAnswerId: null,
    form: {},
    timer: null,
    doTime: 0,
    userInfo: null,
    remainTime: 0,
    remainTimeStr: null,
    modalShow: false,
    result: 0,
    timeOutShow: false,
    address: "未打开地理位置授权！",
    latitude: null,
    longitude: null,
    //图片信息
    paper:null,
    pageNew:0,
    //是否是首页
    isFristPage:true,
    //是否是最后一页
    isLastPage:false,
    //是否开始标注
    canBiaoZhu:false,
    //图片id
    imageId:null,
    //错误信息
    errorMsg:null,
    //正确信息
    rightMsg:null,
    //正确个数
    rightNum:0
  },
//标注的实现
handleImageTap(e) {
  if (this.data.canBiaoZhu) {
    const touch = e.touches[0];
    const x0 = touch.pageX; // 获取触摸点在页面中的水平坐标
    const y0 = touch.pageY; // 获取触摸点在页面中的垂直坐标

    const imageRect = wx.createSelectorQuery().select('.image').boundingClientRect();
    imageRect.exec((rect) => {
      const imageX = rect[0].left; // 获取图片在页面中的水平位置
      const imageY = rect[0].top; // 获取图片在页面中的垂直位置

      const relativeX = x0 - imageX; // 计算触摸点相对于图片左上角的水平坐标
      const relativeY = y0 - imageY; // 计算触摸点相对于图片左上角的垂直坐标
      //进行转换  *2  /1.2
      const relativeX1 = relativeX * 2 /1.2;
      const relativeY1 = relativeY * 2 /1.2
      //转换为int
      const relativeX2= parseInt(relativeX1);
      const relativeY2=parseInt(relativeY1);
      console.log("坐标:", relativeX2, relativeY2);
      //开始发送请求
      var token = wx.getStorageSync('token');
      wx.request({
        url: 'http://60.216.100.50:9006/ruoyi-api/imgExamination/imgExamination/contrastCoordinate',
        method:"POST",
        header: {
          'Authorization': 'Bearer ' + token, // 在请求头中携带 token
          },
        data: {
          id: this.data.imageId,
          x:relativeX2 ,
          y:relativeY2
        },
        success: (res) => {
          var data = res.data.data;
          console.log(data); 

          //如果状态码是500，提示客户回答错误，弹出提示框
          if (data.aboolean==1) {
            this.setData({
              errorMsg:11
            })
            wx.showToast({
              title:"再仔细看一下哦" ,
              icon: 'none',
              duration: 1000
            });
          }
        
          // 如果状态码是200，表示客户回答正确，标出图片问题所在
          if (data.aboolean==0) {
           this.setData({
              rightMsg:data.errText,
            })
            wx.showToast({
              icon: 'success',
              duration: 1000
            });
          }

          //自动跳转下一页
          // setTimeout(() => {
          //   var imgExamNum= wx.getStorageSync('imgExamNum');
          //   if (this.data.pageNew+1<imgExamNum) {
          //     this.nextPage();
          //   }
          // }, 1500);
        },
        fail: function(err) {
          // 处理请求失败
          console.error(err);
        }
      })
    });
  }
},

//开始标注功能的实现
startDo(){
  this.setData({
    canBiaoZhu:true
  })
  console.log(this.data.canBiaoZhu);
},

//标注完成功能的实现
Docompelte(){
  this.setData({
    canBiaoZhu:false
  })
},

//上一页功能实现
backPage(){
    var token = wx.getStorageSync('token');
    var paperId =wx.getStorageSync('imgExamId');
    var pageNew=this.data.pageNew-1;
    this.setData({
      pageNew:pageNew,
      isLastPage: false // 设置为第一页
    })
    wx.request({
      url: 'http://60.216.100.50:9006/ruoyi-api/system/examinationImg/get1List',
      method:"POST",
      header: {
        'Authorization': 'Bearer ' + token, // 在请求头中携带 token
        },
        data: {
          pageNew: pageNew,
        },
        success: (res) => {
          var data = res.data;
          console.log(data);
          // 处理查询结果
          this.setData({
            paper: data.imgUrl,
            imageId:data.id
          });    
          console.log(this.data.imageId)
          if (pageNew === 0) {
            this.setData({
              isFristPage: true // 设置为第一页
            });
            wx.showToast({
              title: '这已经是首页',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: function(err) {
          // 处理请求失败
          console.error(err);
        }
    })
  },

//下一页功能实现
  nextPage(){
    var token = wx.getStorageSync('token');
    var paperId =wx.getStorageSync('imgExamId');
    var pageNew=this.data.pageNew+1;
    this.setData({
      pageNew:pageNew,
      isFristPage: false,
      rightMsg:null
    })
    wx.request({
      url: 'http://60.216.100.50:9006/ruoyi-api/system/examinationImg/get1List',
      method:"POST",
      header: {
        'Authorization': 'Bearer ' + token, // 在请求头中携带 token
        },
        data: {
          pageNew: pageNew,
        },
        success: (res) => {
          var data = res.data;
          console.log(data);
          // 处理查询结果
          this.setData({
            paper: data.imgUrl,
            imageId:data.id
          });    
          console.log(this.data.imageId);
          if (data.imgUrl==null) {
            this.setData({
              isLastPage: true, // 设置为最后一页
            });
            wx.showToast({
              title: '当前是最后一页',
              icon: 'none',
              duration: 2000
            });
            return;
          }
        },
        fail: function(err) {
          // 处理请求失败
          console.error(err);
        }
    })
  },

//提交方式
imgExamSubmit() {
  wx.showModal({
    title: '练习完成',
    content: '恭喜您完成练习！您可以点击上方返回按钮返回进行考试，预祝您取得优异成绩！',
    showCancel: false,
    confirmText: '确定',
    success: function(res) {
      // 用户点击确定按钮后的回调函数
      if (res.confirm) {
        // 在这里可以执行其他操作
        console.log('用户点击确定');
      }
    }
  });
},
  onShow: function () {

  },

  onLoad: function (options) {
    var token = wx.getStorageSync('token');
    var pageNew = this.data.pageNew;
    var that = this; // 保存 this 到变量 that
  
    wx.request({
      url: 'http://60.216.100.50:9006/ruoyi-api/picturePaper/picturePaper/createPaper1',
      method: "POST",
      header: {
        'Authorization': 'Bearer ' + token,
      },
      success: function (res) {
        var data = res.data;
        console.log(data);
        if (data.code == 200) {
          console.log("生成试卷成功");
          wx.request({
            url: 'http://60.216.100.50:9006/ruoyi-api/system/examinationImg/get1List',
            method: "POST",
            header: {
              'Authorization': 'Bearer ' + token,
            },
            data: {
              pageNew: pageNew
            },
            success: function (res) {
              var data = res.data;
              that.setData({ // 使用 that 调用 setData 方法
                paper: data.imgUrl,
                imageId:data.id
              });
            },
            fail: function (err) {
              console.error(err);
            }
          })
        }
      },
      fail: function (err) {
        console.error(err);
      }
    })
  },

// var data = JSON.parse(decodeURIComponent(options.data)); // 解析传递的试题数据
// console.log(data);
// this.setData({
//   paper: data.imgUrl, // 将试题数据设置到页面的data中
//   imageId:data.id
// });
// console.log(this.data.imageId)


    // wx.enableAlertBeforeUnload({
    //   message: '确认退出考试？退出考试将自动提交试卷！',
    //   success: res => {
    //     wx.vibrateShort({
    //       type: 'heavy'
    //     })
    //   },
    //   fail: err => {}
    // });

    // wx.onUserCaptureScreen(function (res) {
    //   wx.showModal({
    //     title: '提示',
    //     content: '严禁截屏，如有下次，自动提交试卷！'
    //   })
    // });



  onUnload() {
    clearInterval(this.data.timer)
  },

  returnRecord() {
    // wx.reLaunch({
    //   url: '/pages/record/index',
    // });
    app.globalData.examPaperAnswerId = this.data.examPaperAnswerId,
      // app.globalData.userScore =  this.data.score,
      console.log("我要传输的ID是" + this.data.examPaperAnswerId),
      wx.navigateTo({
        url: '/packageF/exam/result/index?id=' + app.globalData.examPaperAnswerId,
      })
  },

  formSubmit: function (e) {
    let _this = this
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    e.detail.value.id = this.data.paperId
    e.detail.value.doTime = this.data.doTime
    e.detail.value.address = this.data.address
    e.detail.value.latitude = this.data.latitude
    e.detail.value.longitude = this.data.longitude
    let title = this.data.form.name
    app.formPost('/api/wx/student/exampaper/answer/answerSubmit', e.detail.value)
      .then(res => {
        if (res.code === 1) {
          _this.setData({
            modalShow: true,
            result: res.response.score,
            examPaperAnswerId: res.response.examPaperAnswerId
          });
          app.globalData.userScore = res.response.score
          let fenshu = res.response.score;
          console.log(fenshu);
          let userName = _this.data.userInfo.realName;
          console.log(userName);
          let paperScore = (_this.data.score * 0.6).toFixed();
          console.log(paperScore);
          let address = _this.data.address
          console.log(address)
          wx.cloud.callFunction({
            name: 'getOpenId'
          }).then(res => {
            console.log(res);
            let openid = res.result.openid
            console.log("获取openid成功！", openid)
            wx.cloud.callFunction({
              config: {
                env: 'dabenben-jrvrn'
              },
              // 要调用的云函数名称
              name: 'sendNewMsg',
              // 传递给云函数的参数
              data: {
                openid: openid,
                // theme:"本次考试"+jige+",有问题联系陈鹏！",
                theme: address,
                number: fenshu,
                title: title,
                username: userName,
                bukao: "本次考试及格分：" + paperScore + "分"
              },
              success: res => {
                console.log(res)
              },
              fail: err => {
                console.log(err)
              },
            })
          })
          wx.vibrateShort({
            type: 'medium'
          })
        } else {
          app.message(res.response, 'error')
        }
        wx.hideLoading()
      }).catch(e => {
        wx.hideLoading()
        app.message(e, 'error')
      })
  }
})